package com.ailot.cloud.upms.api.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ailot.cloud.upms.api.datasource.DynamicDataSourceService;
import com.ailot.cloud.upms.api.mapper.SysDatasourceMapper;
import com.ailot.cloud.upms.api.service.SysDatasourceService;
import com.ailot.cloud.upms.common.entity.SysDatasource;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

/**
 * @Author : litao
 * @create 2023/12/7 11:03
 */

@Service
@AllArgsConstructor
public class SysDatasourceServiceImpl extends ServiceImpl<SysDatasourceMapper, SysDatasource> implements SysDatasourceService {

    private final DynamicDataSourceService dynamicDataSourceService;

    @Override
    public void addSysDatasource(SysDatasource sysDatasource) throws SQLException {
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setPoolName(sysDatasource.getName());
        dataSourceProperty.setUrl(sysDatasource.getUrl());
        dataSourceProperty.setUsername(sysDatasource.getUsername());
        dataSourceProperty.setPassword(sysDatasource.getPassword());
        //校验数据源配置是否能链接
        dynamicDataSourceService.checkDataSource(dataSourceProperty);
        //添加动态数据源
        dynamicDataSourceService.addDataSource(dataSourceProperty);

        this.baseMapper.insert(sysDatasource);
    }

    @Override
    public void updateSysDatasource(SysDatasource sysDatasource) throws SQLException {
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setPoolName(sysDatasource.getName());
        dataSourceProperty.setUrl(sysDatasource.getUrl());
        dataSourceProperty.setUsername(sysDatasource.getUsername());
        dataSourceProperty.setPassword(sysDatasource.getPassword());
        //校验数据源配置是否能链接
        dynamicDataSourceService.checkDataSource(dataSourceProperty);
        //先删除动态数据源
        dynamicDataSourceService.removeDataSource(baseMapper.selectById(sysDatasource.getId()).getName());
        //再添加动态数据源
        dynamicDataSourceService.addDataSource(dataSourceProperty);

        this.baseMapper.updateById(sysDatasource);
    }
}
